﻿using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractMes;
using HamcoWcs.Contract.ContractPcon.IPconDbMsgParsers;
using HamcoWcs.DAL;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.Devices;
using HamcoWcs.Models.TibcoMessage;
using HamcoWcs.Service.Common;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;

namespace HamcoWcs.Service.Srm.SrmTaskParsers
{
    /// <summary>堆垛机任务完成</summary>
    public class SrmParser_TaskFinish : SrmParserBase
    {





        public override void Deal(SrmDto srm, SrmPlc srmPlc)
        {
            var taskEntity = _wcsDbContext.SubTasks
                                          .Where(x => x.PlcName == srm.SrmName)
                                          .Where(x => x.TaskStatus == EnumSubTaskStatus.OnProgress.ToString())
                                          .Include(x => x.MainTask)
                                          .FirstOrDefault();

            if (taskEntity == null)
            {
                _logger.AddWcsRunLog(srm.UnitId, $"{srm.MachineName}-{srm.PortName}无正在执行的任务，任务完成处理失败");
                return;
            }

            if (taskEntity.MainTask.MainTaskType == nameof(EnumMainTaskType.SrmCycleTask))
            {
                if (taskEntity.IsNeedSection)
                {
                    //if (srm.Aisle.AisleMode == EnumSrmAisleMode.Normal)
                    //{
                    var asrm = srm.AnotherSrm;
                    taskEntity.PlcName = asrm.SrmName;
                    taskEntity.FromLoc = taskEntity.HandOffShelf;
                    taskEntity.IsNeedSection = false;
                    //taskEntity.MainTask.Priority = "101";

                    var loc = _locationService.GetLocationByWcsName(taskEntity.HandOffShelf);
                    loc.UnitId = taskEntity.UnitId;
                    loc.LocStatus = (int)EnumLocStatus.Out;

                    if (taskEntity.ToLoc.IsShelf())
                    {
                        taskEntity.SubTaskType = EnumSubTaskType.SrmMoveTask.ToString();
                    }
                    else
                    {
                        taskEntity.SubTaskType = EnumSubTaskType.SrmOutTask.ToString();
                    }
                    taskEntity.TaskStatus = EnumSubTaskStatus.Ready.ToString();
                    _wcsDbContext.SaveChanges();
                    return;
                }

                _baseTaskService.UpdateSubTaskStatus(taskEntity.Id, EnumSubTaskStatus.Finished);
                return;
            }


            // 搬送完成获取计划信息
            if (taskEntity.FromLoc.Contains("CJRCV") && taskEntity.ToLoc.IsShelf())
            {
                _mesCommunicateService.CurrentStockerEmptyBoxPlanRequest(srm.Aisle.NodeName);
            }

            if (taskEntity.SubTaskType == EnumSubTaskType.SrmAbnormalInboundTask.ToString())
            {
                if (taskEntity.MainTask.MainTaskType == EnumMainTaskType.InventoryTask.ToString())
                {
                    var loc = _locationService.GetLocationByWcsName(taskEntity.ToLoc);
                    loc.LocStatus = (int)EnumLocStatus.Store;
                    _locationService.ShelfBlock(loc.WcsLocName, "WCS", "盘点时读码异常，SRM上报错误");
                }
                else
                {
                    // 异常入库
                    var loc = _locationService.GetLocationByWcsName(taskEntity.ToLoc);

                    loc.LocStatus = (int)EnumLocStatus.Store;
                    loc.UnitId = taskEntity.UnitId;
                    _wcsDbContext.SaveChanges();
                    _locationService.ShelfBlock(loc.WcsLocName, "WCS", loc.Remark);

                    taskEntity.MainTask.CurrentMachine = loc.Aisle;
                    taskEntity.MainTask.CurrentPosition = loc.WcsLocName;
                    taskEntity.MainTask.CurrentType = "SHELF";
                    taskEntity.MainTask.CurrentZone = loc.ZoneName;

                    taskEntity.TaskStatus = EnumSubTaskStatus.Finished.ToString();
                    taskEntity.MainTask.TaskStatus = EnumMainTaskStatus.Cancel.ToString();
                    taskEntity.MainTask.ReasonCode = "1002";//读码异常
                    _wcsDbContext.SaveChanges();
                    return;
                }

            }


            if (taskEntity.SubTaskType == EnumSubTaskType.SrmInTask.ToString()
            || taskEntity.SubTaskType == EnumSubTaskType.SrmMoveTask.ToString() && !taskEntity.IsNeedSection)
            {
                // 入库完成修改货位状态并上报托盘位置变化
                var loc = _wcsDbContext.WcsLocations.FirstOrDefault(x => x.WcsLocName == taskEntity.ToLoc);
                loc.LocStatus = (int)EnumLocStatus.Store;
                loc.UnitId = taskEntity.UnitId;
                if (taskEntity.UnitId.Contains("UNKNOWN"))
                {
                    loc.IsLock = true;
                    loc.Remark = $"超时自动入库+{srm.SrmName}";
                }
                _wcsDbContext.SaveChanges();

                var zoneData = _locationService.InventoryZonesByZone(loc.ZoneName);
                _mesCommunicateService.InventoryZoneDataRequest(new InventoryZoneDataReportMessage(
                    new InventoryZoneDataReportMessageBody(loc.Aisle, zoneData)));


                taskEntity.MainTask.CurrentMachine = srm.MachineName;
                taskEntity.MainTask.CurrentPosition = srm.PortName;
                taskEntity.MainTask.CurrentType = "PORT";
                taskEntity.MainTask.CurrentZone = "";

                _mesCommunicateService.PalletLocationChanged(new PalletLocationChangedMessage(new PalletLocationChangedMessageBody()
                {
                    PalletName = srm.UnitId,
                    TransportJobName = taskEntity.MainTask.TaskId,
                    CurrentMachineName = srm.Aisle.NodeName,
                    CurrentPositionName = loc.WcsLocName,
                    CurrentPositionType = "SHELF",
                    TransferState = "INSTK",
                    CurrentZoneName = loc.ZoneName,
                }));
            }

            if (taskEntity.IsNeedSection)
            {
                //if (srm.Aisle.AisleMode == EnumSrmAisleMode.Normal)
                //{
                var asrm = srm.AnotherSrm;
                taskEntity.PlcName = asrm.SrmName;
                taskEntity.FromLoc = taskEntity.HandOffShelf;
                taskEntity.IsNeedSection = false;
                //taskEntity.MainTask.Priority = "101";

                var loc = _locationService.GetLocationByWcsName(taskEntity.HandOffShelf);
                loc.UnitId = taskEntity.UnitId;
                loc.LocStatus = (int)EnumLocStatus.Out;

                if (taskEntity.ToLoc.IsShelf())
                {
                    taskEntity.SubTaskType = EnumSubTaskType.SrmMoveTask.ToString();
                }
                else
                {
                    taskEntity.SubTaskType = EnumSubTaskType.SrmOutTask.ToString();
                }
                taskEntity.TaskStatus = EnumSubTaskStatus.Ready.ToString();
                _wcsDbContext.SaveChanges();
                return;
                

            }

            _baseTaskService.UpdateSubTaskStatus(taskEntity.Id, EnumSubTaskStatus.Finished);
        }

        private readonly IBaseTaskService _baseTaskService;
        private readonly AutomaticStorageInfo _asrs;
        public override EnumSrmRequest RequestType => EnumSrmRequest.TaskFinish;

        public SrmParser_TaskFinish(ILocationService locationService, WcsDbContext wcsDbContext,
            IMesCommunicateService mesCommunicateService, IBaseTaskService baseTaskService,
            ILoggerService logger, AutomaticStorageInfo asrs)
            : base(wcsDbContext, locationService, mesCommunicateService, logger)
        {
            _baseTaskService = baseTaskService;
            _asrs = asrs;
        }
    }
}
